package com.ruoyi.iot.modbus.tcp;

import cn.hutool.core.util.NumberUtil;
import com.ruoyi.iot.utils.ModbusCache;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: CreateTCPMasterUtils
 * @Author: Howe
 * @Date: 2019/11/28 11:21
 */
public class CreateTCPMasterUtils {
    /**
     * 初始化modbusFactory
     */
    static ModbusFactory modbusFactory;

    static {
        if (modbusFactory == null) {
            modbusFactory = new ModbusFactory();
        }
    }


    /**
     * @Description: 获取master
     * @Param: []
     * @Return: com.serotonin.modbus4j.ModbusMaster
     * @Author: How
     * @Date: 2019/11/28 11:22
     */
    public static ModbusMaster getTCPMaster(IpParameters params) {
        //TCP协议
        ModbusMaster master = modbusFactory.createTcpMaster(params, false);
        try {
            master.init();
        } catch (ModbusInitException e) {
            e.printStackTrace();
        }
        return master;
    }


    /**
     * @Description: 获取master
     * @Param: []
     * @Return: com.serotonin.modbus4j.ModbusMaster
     * @Author: How
     * @Date: 2019/11/28 11:22
     */
    public static Map<String, ModbusMaster> getTCPMasterMap() {
        Map<String, ModbusMaster> ModbusTCPMasterMap = new HashMap<>();
        Map<String, SerialTcp> serialTcpMaps = ModbusCache.getSerialTcpMap();
        for (Map.Entry<String, SerialTcp> serialTcpMap : serialTcpMaps.entrySet()) {
            String mapKey = serialTcpMap.getKey();
            if (ModbusCache.getModbusMaster(mapKey) != null) {
                continue;
            }
            SerialTcp serialTcp = serialTcpMap.getValue();
            IpParameters params = new IpParameters();
            params.setHost(serialTcp.getHost());
            if (NumberUtil.isInteger(serialTcp.getPort())) {
                params.setPort(Integer.parseInt(serialTcp.getPort()));
            } else {
                params.setPort(520);
            }
            params.setEncapsulated(true);
            ModbusMaster master = CreateTCPMasterUtils.getTCPMaster(params);//TCP
            ModbusTCPMasterMap.put(mapKey, master);
        }
        return ModbusTCPMasterMap;
    }
}
